import React, { useState, useEffect, useCallback, useRef } from 'react';
import { 
  Card, 
  Tag, 
  Button, 
  message,
  Modal,
  Image,
  Typography,
  Spin,
  Switch,
  Avatar,
  Dropdown
} from 'antd';
import { 
  ReloadOutlined,
  HeartOutlined,
  HeartFilled,
  CloseOutlined,
  RetweetOutlined,
  SettingOutlined,
  UserOutlined,
  LogoutOutlined
} from '@ant-design/icons';
import { clientApi } from '../../services/api';
import { useNavigate } from 'react-router-dom';
import LoginModal from '../../components/LoginModal';
import { saveUser, getUser, removeUser, isLoggedIn, getUserId, getUserNickname } from '../../utils/auth';
import '../../App.css';

const { Title, Text, Paragraph } = Typography;

const DishList = () => {
  const navigate = useNavigate();
  const [dishes, setDishes] = useState([]);
  const [categories, setCategories] = useState([]);
  const [tags, setTags] = useState([]);
  const [loading, setLoading] = useState(false);
  const [randomLoading, setRandomLoading] = useState(false);
  const [selectedCategory, setSelectedCategory] = useState(null);
  const [selectedTags, setSelectedTags] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(12);
  const [hasMore, setHasMore] = useState(true);
  const [selectedDish, setSelectedDish] = useState(null);
  const [detailVisible, setDetailVisible] = useState(false);
  const [randomDish, setRandomDish] = useState(null);
  const [randomVisible, setRandomVisible] = useState(false);
  
  // 用户相关状态
  const [user, setUser] = useState(getUser());
  const [loginVisible, setLoginVisible] = useState(false);
  const [onlyFavorites, setOnlyFavorites] = useState(false);
  const [favoriteIds, setFavoriteIds] = useState([]);
  
  // 底部菜单状态
  const [activeTab, setActiveTab] = useState('recommend'); // 'recommend' 或 'random'
  
  // 无限滚动相关
  const loadingRef = useRef(false);
  const observerRef = useRef(null);
  const sentinelRef = useRef(null);

  const loadCategories = async () => {
    try {
      const response = await clientApi.getCategories();
      setCategories(response.data || []);
    } catch (error) {
      console.error('加载分类失败:', error);
    }
  };

  const loadTags = async () => {
    try {
      const response = await clientApi.getTags();
      setTags(response.data || []);
    } catch (error) {
      console.error('加载标签失败:', error);
    }
  };

  const loadFavoriteIds = useCallback(async () => {
    if (!user) return;
    try {
      const response = await clientApi.getFavoriteIds(user.id);
      setFavoriteIds(response.data || []);
    } catch (error) {
      console.error('加载收藏列表失败:', error);
    }
  }, [user]);

  const loadDishes = useCallback(async (page = currentPage, reset = false) => {
    if (loadingRef.current) return;
    loadingRef.current = true;
    setLoading(true);
    
    try {
      let response;
      
      if (onlyFavorites && user) {
        // 加载收藏的菜品
        response = await clientApi.getFavoriteList(user.id, page, pageSize);
      } else {
        // 加载所有菜品
        const params = {
          page,
          size: pageSize,
        };
        if (selectedCategory) params.categoryId = selectedCategory;
        if (selectedTags.length > 0) params.tagIds = selectedTags;
        
        response = await clientApi.getDishes(params);
      }
      
      const newDishes = response.data?.records || [];
      const total = response.data?.total || 0;
      
      if (reset) {
        setDishes(newDishes);
        setCurrentPage(1);
      } else {
        setDishes(prev => [...prev, ...newDishes]);
        setCurrentPage(page);
      }
      
      // 计算是否还有更多数据
      setHasMore(newDishes.length === pageSize);
      
    } catch (error) {
      console.error('加载菜品失败:', error);
    } finally {
      setLoading(false);
      loadingRef.current = false;
    }
  }, [pageSize, selectedCategory, selectedTags, onlyFavorites, user]);

  const resetAndLoadDishes = useCallback(() => {
    setDishes([]);
    setCurrentPage(1);
    setHasMore(true);
    loadDishes(1, true);
  }, [loadDishes]);

  const loadMoreDishes = useCallback(() => {
    if (!loadingRef.current && hasMore) {
      loadDishes(currentPage + 1, false);
    }
  }, [currentPage, hasMore, loadDishes]);

  // 加载分类和标签
  useEffect(() => {
    loadCategories();
    loadTags();
    if (user) {
      loadFavoriteIds();
    }
  }, [user, loadFavoriteIds]);

  // 重置数据并加载第一页
  useEffect(() => {
    resetAndLoadDishes();
  }, [selectedCategory, selectedTags, onlyFavorites]);

  // 设置无限滚动观察器
  useEffect(() => {
    if (sentinelRef.current) {
      observerRef.current = new IntersectionObserver(
        (entries) => {
          if (entries[0].isIntersecting && hasMore && !loadingRef.current) {
            loadMoreDishes();
          }
        },
        { threshold: 0.1 }
      );
      observerRef.current.observe(sentinelRef.current);
    }

    return () => {
      if (observerRef.current) {
        observerRef.current.disconnect();
      }
    };
  }, [hasMore, loadMoreDishes]);

  const handleCategoryChange = (value) => {
    setSelectedCategory(value);
  };



  const handleLogin = (userInfo) => {
    setUser(userInfo);
    saveUser(userInfo);
    setLoginVisible(false);
    message.success(`欢迎回来，${userInfo.nickname}！`);
  };

  const handleLogout = () => {
    setUser(null);
    removeUser();
    setOnlyFavorites(false);
    setFavoriteIds([]);
    message.success('已退出登录');
  };

  const toggleFavorite = async (dish) => {
    if (!user) {
      setLoginVisible(true);
      return;
    }

    try {
      const isFav = favoriteIds.includes(dish.id);
      if (isFav) {
        await clientApi.removeFavorite(user.id, dish.id);
        setFavoriteIds(prev => prev.filter(id => id !== dish.id));
        message.success('已取消收藏');
      } else {
        await clientApi.addFavorite(user.id, dish.id);
        setFavoriteIds(prev => [...prev, dish.id]);
        message.success('已添加收藏');
      }
    } catch (error) {
      message.error(error.message || '操作失败');
    }
  };

  const showDishDetail = async (dish) => {
    try {
      const response = await clientApi.getDishDetail(dish.id);
      setSelectedDish(response.data);
      setDetailVisible(true);
    } catch (error) {
      console.error('获取菜品详情失败:', error);
    }
  };

  const handleRandomSelect = async () => {
    setRandomLoading(true);
    try {
      const params = {};
      if (selectedCategory) params.categoryId = selectedCategory;
      if (selectedTags.length > 0) params.tagIds = selectedTags;

      const response = await clientApi.randomSelectDish(
        params, 
        user?.id, 
        onlyFavorites && user
      );
      if (response.data) {
        setRandomDish(response.data);
        setRandomVisible(true);
      } else {
        message.info('没有找到符合条件的菜品');
      }
    } catch (error) {
      console.error('随机选菜失败:', error);
    } finally {
      setRandomLoading(false);
    }
  };

  const handleAcceptDish = async (dishId) => {
    try {
      await clientApi.acceptDish(dishId);
      message.success('已接受这道菜！');
      setRandomVisible(false);
    } catch (error) {
      console.error('接受菜品失败:', error);
    }
  };

  const handleRejectDish = async (dishId, reason = '不想吃') => {
    try {
      await clientApi.rejectDish(dishId, reason);
      message.info('已拒绝这道菜');
      setRandomVisible(false);
    } catch (error) {
      console.error('拒绝菜品失败:', error);
    }
  };

  const getCategoryName = (categoryId) => {
    const category = categories.find(c => c.id === categoryId);
    return category ? category.name : '';
  };

  const getTagColor = (tagId) => {
    const tag = tags.find(t => t.id === tagId);
    return tag ? tag.color : 'default';
  };

  const getTagName = (tagId) => {
    const tag = tags.find(t => t.id === tagId);
    return tag ? tag.name : '';
  };

  const userMenuItems = [
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: handleLogout
    }
  ];

  return (
    <div style={{ 
      background: 'linear-gradient(180deg, #fafafa 0%, #ffffff 50%, #fafafa 100%)', 
      minHeight: '100vh',
      padding: '0'
    }}>
      {/* 顶部标语区域 */}
      <div style={{
        textAlign: 'center',
        padding: '80px 20px 60px',
        background: 'linear-gradient(135deg, #fafafa 0%, #ffffff 100%)',
        position: 'relative',
        borderBottom: '1px solid rgba(0,0,0,0.05)'
      }}>
        {/* 管理后台按钮 */}
        <Button 
          type="text" 
          icon={<SettingOutlined />}
          onClick={() => navigate('/admin')}
          style={{
            position: 'absolute',
            top: '20px',
            right: '20px',
            color: '#999',
            border: 'none',
            background: 'transparent'
          }}
        />
        
        {/* 用户登录/信息区域 */}
        <div style={{
          position: 'absolute',
          top: '20px',
          left: '20px'
        }}>
          {user ? (
            <Dropdown menu={{ items: userMenuItems }} placement="bottomLeft">
              <div style={{
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
                cursor: 'pointer',
                padding: '8px 12px',
                borderRadius: '20px',
                background: '#f5f5f5',
                transition: 'all 0.3s ease'
              }}>
                <Avatar size="small" icon={<UserOutlined />} />
                <span style={{ fontSize: '14px', color: '#666' }}>
                  {user.nickname}
                </span>
              </div>
            </Dropdown>
          ) : (
            <Button 
              type="primary"
              icon={<UserOutlined />}
              onClick={() => setLoginVisible(true)}
              style={{
                borderRadius: '20px',
                border: 'none',
                background: '#1a1a1a'
              }}
            >
              登录
            </Button>
          )}
        </div>
        
        <Title level={1} style={{
          fontSize: 'clamp(32px, 7vw, 48px)',
          fontWeight: '200',
          color: '#1a1a1a',
          margin: '0 0 12px 0',
          letterSpacing: '2px',
          background: 'linear-gradient(135deg, #1a1a1a 0%, #666 100%)',
          WebkitBackgroundClip: 'text',
          WebkitTextFillColor: 'transparent',
          backgroundClip: 'text'
        }}>
          今天吃什么？
        </Title>
        <Text style={{
          fontSize: 'clamp(16px, 3.5vw, 18px)',
          color: '#888',
          fontWeight: '300',
          letterSpacing: '1px'
        }}>
          发现美味，享受生活
        </Text>
      </div>

      {/* 标签筛选区域 */}
image.png      <div style={{
        padding: '0 20px 40px',
        background: 'transparent'
      }}>
        {/* 仅查看收藏开关 */}
        {user && (
          <div style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            marginBottom: '20px',
            gap: '8px'
          }}>
            <HeartFilled style={{ color: onlyFavorites ? '#ff4d4f' : '#d9d9d9' }} />
            <span style={{ fontSize: '14px', color: '#666' }}>仅查看收藏</span>
            <Switch
              checked={onlyFavorites}
              onChange={(checked) => setOnlyFavorites(checked)}
              size="small"
            />
          </div>
        )}
        
        {/* 分类标签 */}
        <div style={{ marginBottom: '20px' }}>
          <div style={{
            display: 'flex',
            overflowX: 'auto',
            gap: '12px',
            paddingBottom: '8px',
            scrollbarWidth: 'none',
            msOverflowStyle: 'none'
          }}>
            <div 
              onClick={() => handleCategoryChange(null)}
              style={{
                padding: '10px 24px',
                borderRadius: '25px',
                border: 'none',
                background: selectedCategory === null ? 'linear-gradient(135deg, #1a1a1a 0%, #333 100%)' : 'rgba(255,255,255,0.8)',
                color: selectedCategory === null ? '#fff' : '#666',
                cursor: 'pointer',
                whiteSpace: 'nowrap',
                fontSize: '14px',
                fontWeight: '500',
                transition: 'all 0.4s cubic-bezier(0.4, 0, 0.2, 1)',
                boxShadow: selectedCategory === null ? '0 4px 16px rgba(26,26,26,0.3)' : '0 2px 8px rgba(0,0,0,0.06)',
                backdropFilter: 'blur(10px)'
              }}
            >
              全部
            </div>
            {categories.map(category => (
              <div 
                key={category.id}
                onClick={() => handleCategoryChange(category.id)}
                style={{
                  padding: '10px 24px',
                  borderRadius: '25px',
                  border: 'none',
                  background: selectedCategory === category.id ? 'linear-gradient(135deg, #1a1a1a 0%, #333 100%)' : 'rgba(255,255,255,0.8)',
                  color: selectedCategory === category.id ? '#fff' : '#666',
                  cursor: 'pointer',
                  whiteSpace: 'nowrap',
                  fontSize: '14px',
                  fontWeight: '500',
                  transition: 'all 0.4s cubic-bezier(0.4, 0, 0.2, 1)',
                  boxShadow: selectedCategory === category.id ? '0 4px 16px rgba(26,26,26,0.3)' : '0 2px 8px rgba(0,0,0,0.06)',
                  backdropFilter: 'blur(10px)'
                }}
              >
                {category.name}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* 菜品列表 */}
      <div style={{
        padding: '0 20px 120px',
        background: 'transparent'
      }}>
        <Spin spinning={loading}>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
            gap: '24px',
            maxWidth: '1200px',
            margin: '0 auto'
          }}>
            {dishes.map(dish => (
              <div
                key={dish.id}
                style={{
                  background: '#fff',
                  borderRadius: '20px',
                  overflow: 'hidden',
                  transition: 'all 0.4s cubic-bezier(0.4, 0, 0.2, 1)',
                  border: '1px solid rgba(0,0,0,0.06)',
                  position: 'relative',
                  boxShadow: '0 2px 12px rgba(0,0,0,0.04)'
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.transform = 'translateY(-8px) scale(1.02)';
                  e.currentTarget.style.boxShadow = '0 12px 40px rgba(0,0,0,0.15)';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.transform = 'translateY(0) scale(1)';
                  e.currentTarget.style.boxShadow = '0 2px 12px rgba(0,0,0,0.04)';
                }}
              >
                <div 
                  onClick={() => showDishDetail(dish)}
                  style={{
                    width: '100%',
                    height: '200px',
                    overflow: 'hidden',
                    position: 'relative',
                    cursor: 'pointer'
                  }}
                >
                  <img
                    src={dish.mainImage}
                    alt={dish.name}
                    style={{
                      width: '100%',
                      height: '100%',
                      objectFit: 'cover',
                      transition: 'transform 0.3s ease'
                    }}
                    onError={(e) => {
                      e.target.src = '';
                    }}
                  />
                  <div style={{
                    position: 'absolute',
                    top: '12px',
                    right: '12px',
                    background: 'rgba(255,255,255,0.9)',
                    padding: '4px 8px',
                    borderRadius: '12px',
                    fontSize: '12px',
                    color: '#666',
                    fontWeight: '500'
                  }}>
                    {dish.calories} 卡
                  </div>
                </div>
                
                {/* 收藏按钮 */}
                {user && (
                  <div
                    onClick={(e) => {
                      e.stopPropagation();
                      toggleFavorite(dish);
                    }}
                    style={{
                      position: 'absolute',
                      top: '12px',
                      left: '12px',
                      background: 'rgba(255,255,255,0.9)',
                      borderRadius: '50%',
                      width: '32px',
                      height: '32px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      cursor: 'pointer',
                      transition: 'all 0.3s ease',
                      zIndex: 2
                    }}
                  >
                    <HeartFilled 
                      style={{
                        color: favoriteIds.includes(dish.id) ? '#ff4d4f' : '#d9d9d9',
                        fontSize: '16px'
                      }} 
                    />
                  </div>
                )}
                <div style={{
                  padding: '16px'
                }}>
                  <h3 style={{
                    margin: '0 0 8px 0',
                    fontSize: '16px',
                    fontWeight: '500',
                    color: '#1a1a1a',
                    lineHeight: '1.4'
                  }}>
                    {dish.name}
                  </h3>
                  <p style={{
                    margin: '0 0 12px 0',
                    fontSize: '14px',
                    color: '#999',
                    lineHeight: '1.4'
                  }}>
                    {getCategoryName(dish.categoryId)}
                  </p>
                  {dish.tagIds && dish.tagIds.length > 0 && (
                    <div style={{
                      display: 'flex',
                      flexWrap: 'wrap',
                      gap: '6px'
                    }}>
                      {dish.tagIds.slice(0, 3).map(tagId => (
                        <span
                          key={tagId}
                          style={{
                            padding: '2px 8px',
                            borderRadius: '8px',
                            fontSize: '12px',
                            background: '#f5f5f5',
                            color: '#666',
                            fontWeight: '400'
                          }}
                        >
                          {getTagName(tagId)}
                        </span>
                      ))}
                      {dish.tagIds.length > 3 && (
                        <span style={{
                          padding: '2px 8px',
                          borderRadius: '8px',
                          fontSize: '12px',
                          background: '#f5f5f5',
                          color: '#666',
                          fontWeight: '400'
                        }}>
                          +{dish.tagIds.length - 3}
                        </span>
                      )}
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
          
          {/* 无限滚动哨兵元素 */}
          {hasMore && (
            <div 
              ref={sentinelRef}
              style={{
                height: '20px',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                margin: '20px 0'
              }}
            >
              {loadingRef.current && (
                <Spin size="small" />
              )}
            </div>
          )}
        </Spin>
      </div>



      {/* 底部菜单 */}
      <div style={{
        position: 'fixed',
        bottom: '20px',
        left: '50%',
        transform: 'translateX(-50%)',
        zIndex: 1000,
        width: '280px',
        height: '60px'
      }}>
        <div style={{
          position: 'relative',
          width: '100%',
          height: '100%',
          background: '#ffffff',
          borderRadius: '30px',
          padding: '4px',
          boxShadow: '0 8px 32px rgba(0,0,0,0.08), 0 2px 8px rgba(0,0,0,0.04)',
          overflow: 'hidden',
          border: '1px solid rgba(0, 0, 0, 0.06)'
        }}>
          {/* 选中tab的背景 */}
          <div style={{
            position: 'absolute',
            top: '4px',
            left: activeTab === 'recommend' ? '4px' : 'calc(70% + 4px)',
            width: activeTab === 'recommend' ? '70%' : '30%',
            height: 'calc(100% - 8px)',
            background: activeTab === 'recommend' ? '#2c3e50' : '#e74c3c',
            borderRadius: '26px',
            transition: 'all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94)',
            boxShadow: '0 4px 12px rgba(0,0,0,0.1), 0 1px 4px rgba(0,0,0,0.06)',
            zIndex: 1
          }} />
          
          {/* 简洁分割线 */}
          <div style={{
            position: 'absolute',
            top: '25%',
            left: '70%',
            width: '1px',
            height: '50%',
            background: 'rgba(0,0,0,0.08)',
            borderRadius: '1px',
            transition: 'all 0.4s ease',
            zIndex: 2,
            opacity: 0.5
          }} />
          
          {/* 推荐按钮 */}
          <button
            onClick={() => setActiveTab('recommend')}
            style={{
              position: 'absolute',
              top: '0',
              left: '0',
              width: '70%',
              height: '100%',
              border: 'none',
              background: 'transparent',
              color: activeTab === 'recommend' ? '#ffffff' : '#666',
              fontSize: '15px',
              fontWeight: '500',
              cursor: 'pointer',
              zIndex: 3,
              transition: 'all 0.3s ease',
              borderRadius: '26px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: '6px'
            }}
          >
            <span style={{
              fontSize: '16px'
            }}>💼</span>
            <span>推荐</span>
          </button>
          
          {/* 随机按钮 */}
          <button
            onClick={() => {
              setActiveTab('random');
              if (!randomLoading) {
                handleRandomSelect();
              }
            }}
            disabled={randomLoading}
            style={{
              position: 'absolute',
              top: '0',
              right: '0',
              width: '30%',
              height: '100%',
              border: 'none',
              background: 'transparent',
              color: activeTab === 'random' ? '#ffffff' : '#666',
              fontSize: '13px',
              fontWeight: '500',
              cursor: randomLoading ? 'not-allowed' : 'pointer',
              zIndex: 3,
              transition: 'all 0.3s ease',
              borderRadius: '26px',
              opacity: randomLoading ? 0.7 : 1,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              flexDirection: 'column',
              gap: '2px'
            }}
          >
            <span style={{
              fontSize: '16px'
            }}>
              {randomLoading ? '⏳' : '🎯'}
            </span>
            <span style={{ fontSize: '11px' }}>随机</span>
          </button>
        </div>
      </div>

      {/* 菜品详情弹窗 */}
      <Modal
        title={null}
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
        width={window.innerWidth <= 768 ? '95%' : 600}
        centered
        styles={{
          body: { padding: '32px' },
          mask: { backgroundColor: 'rgba(0, 0, 0, 0.6)' }
        }}
        style={{
          borderRadius: '16px',
          overflow: 'hidden'
        }}
      >
        {selectedDish && (
          <div>
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <Image
                src={selectedDish.mainImage}
                alt={selectedDish.name}
                style={{ 
                  width: '100%', 
                  height: '240px', 
                  objectFit: 'cover',
                  borderRadius: '12px'
                }}
                fallback=""
              />
            </div>
            <Title level={3} style={{ 
              textAlign: 'center', 
              marginBottom: 24,
              fontSize: '24px',
              fontWeight: '500',
              color: '#1a1a1a'
            }}>
              {selectedDish.name}
            </Title>
            
            <div style={{ 
              display: 'flex', 
              flexDirection: 'column', 
              gap: '16px'
            }}>
              <div style={{ 
                display: 'flex', 
                alignItems: 'center',
                padding: '12px 0',
                borderBottom: '1px solid #f0f0f0'
              }}>
                <Text style={{ 
                  fontSize: '14px', 
                  color: '#666',
                  minWidth: '60px'
                }}>分类</Text>
                <Tag color="default" style={{
                  borderRadius: '20px',
                  padding: '4px 12px',
                  border: 'none',
                  background: '#f5f5f5',
                  color: '#666'
                }}>
                  {getCategoryName(selectedDish.categoryId)}
                </Tag>
              </div>
              
              <div style={{ 
                display: 'flex', 
                alignItems: 'center',
                padding: '12px 0',
                borderBottom: '1px solid #f0f0f0'
              }}>
                <Text style={{ 
                  fontSize: '14px', 
                  color: '#666',
                  minWidth: '60px'
                }}>标签</Text>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
                  {selectedDish.tags?.map(tag => (
                    <Tag key={tag.id} color={getTagColor(tag.id)} style={{
                      borderRadius: '20px',
                      padding: '4px 12px',
                      border: 'none'
                    }}>
                      {tag.name}
                    </Tag>
                  ))}
                </div>
              </div>
              
              <div style={{ 
                display: 'flex', 
                alignItems: 'center',
                padding: '12px 0',
                borderBottom: selectedDish.description ? '1px solid #f0f0f0' : 'none'
              }}>
                <Text style={{ 
                  fontSize: '14px', 
                  color: '#666',
                  minWidth: '60px'
                }}>热量</Text>
                <Text style={{ fontSize: '16px', fontWeight: '500' }}>
                  {selectedDish.calories} 卡路里
                </Text>
              </div>
              
              {selectedDish.description && (
                <div style={{ padding: '12px 0' }}>
                  <Text style={{ 
                    fontSize: '14px', 
                    color: '#666',
                    display: 'block',
                    marginBottom: '8px'
                  }}>描述</Text>
                  <Paragraph style={{ 
                    fontSize: '14px',
                    lineHeight: '1.6',
                    color: '#333',
                    margin: 0
                  }}>
                    {selectedDish.description}
                  </Paragraph>
                </div>
              )}
            </div>
          </div>
        )}
      </Modal>

      {/* 随机选菜结果弹窗 */}
      <Modal
        title={null}
        open={randomVisible}
        onCancel={() => setRandomVisible(false)}
        footer={null}
        width={window.innerWidth <= 768 ? '95%' : 600}
        centered
        styles={{
          body: { padding: '32px' },
          mask: { backgroundColor: 'rgba(0, 0, 0, 0.6)' }
        }}
        style={{
          borderRadius: '16px',
          overflow: 'hidden'
        }}
      >
        {randomDish && (
          <div>
            <div style={{
              fontSize: '24px',
              fontWeight: '500',
              color: '#1a1a1a',
              textAlign: 'center',
              marginBottom: '24px'
            }}>
              🎲 为你推荐
            </div>
            
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <Image
                src={randomDish.mainImage}
                alt={randomDish.name}
                style={{ 
                  width: '100%', 
                  height: '240px', 
                  objectFit: 'cover',
                  borderRadius: '12px'
                }}
                fallback=""
              />
            </div>
            
            <Title level={3} style={{ 
              textAlign: 'center', 
              marginBottom: 24,
              fontSize: '24px',
              fontWeight: '500',
              color: '#1a1a1a'
            }}>
              {randomDish.name}
            </Title>
            
            <div style={{ 
              display: 'flex', 
              flexDirection: 'column', 
              gap: '16px'
            }}>
              <div style={{ 
                display: 'flex', 
                alignItems: 'center',
                padding: '12px 0',
                borderBottom: '1px solid #f0f0f0'
              }}>
                <Text style={{ 
                  fontSize: '14px', 
                  color: '#666',
                  minWidth: '60px'
                }}>分类</Text>
                <Tag color="default" style={{
                  borderRadius: '20px',
                  padding: '4px 12px',
                  border: 'none',
                  background: '#f5f5f5',
                  color: '#666'
                }}>
                  {getCategoryName(randomDish.categoryId)}
                </Tag>
              </div>
              
              <div style={{ 
                display: 'flex', 
                alignItems: 'center',
                padding: '12px 0',
                borderBottom: '1px solid #f0f0f0'
              }}>
                <Text style={{ 
                  fontSize: '14px', 
                  color: '#666',
                  minWidth: '60px'
                }}>标签</Text>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
                  {randomDish.tags?.map(tag => (
                    <Tag key={tag.id} color={getTagColor(tag.id)} style={{
                      borderRadius: '20px',
                      padding: '4px 12px',
                      border: 'none'
                    }}>
                      {tag.name}
                    </Tag>
                  ))}
                </div>
              </div>
              
              <div style={{ 
                display: 'flex', 
                alignItems: 'center',
                padding: '12px 0',
                borderBottom: randomDish.description ? '1px solid #f0f0f0' : 'none'
              }}>
                <Text style={{ 
                  fontSize: '14px', 
                  color: '#666',
                  minWidth: '60px'
                }}>热量</Text>
                <Text style={{ fontSize: '16px', fontWeight: '500' }}>
                  {randomDish.calories} 卡路里
                </Text>
              </div>
              
              {randomDish.description && (
                <div style={{ padding: '12px 0' }}>
                  <Text style={{ 
                    fontSize: '14px', 
                    color: '#666',
                    display: 'block',
                    marginBottom: '8px'
                  }}>描述</Text>
                  <Paragraph style={{ 
                    fontSize: '14px',
                    lineHeight: '1.6',
                    color: '#333',
                    margin: 0
                  }}>
                    {randomDish.description}
                  </Paragraph>
                </div>
              )}
              
              <div style={{
                display: 'flex',
                gap: '12px',
                justifyContent: 'center',
                marginTop: '24px'
              }}>
                <Button 
                  icon={<CloseOutlined />}
                  onClick={() => handleRejectDish(randomDish?.id)}
                  style={{
                    borderRadius: '20px',
                    padding: '8px 20px',
                    height: 'auto',
                    border: '1px solid #d9d9d9'
                  }}
                >
                  不想吃
                </Button>
                <Button 
                  type="primary" 
                  icon={<HeartOutlined />}
                  onClick={() => handleAcceptDish(randomDish?.id)}
                  style={{
                    background: '#1a1a1a',
                    borderColor: '#1a1a1a',
                    borderRadius: '20px',
                    padding: '8px 20px',
                    height: 'auto'
                  }}
                >
                  就是它了！
                </Button>
              </div>
            </div>
          </div>
        )}
      </Modal>

      {/* 登录模态框 */}
      <LoginModal
        visible={loginVisible}
        onCancel={() => setLoginVisible(false)}
        onSuccess={handleLogin}
      />
    </div>
  );
};

export default DishList;